# -*- coding: utf-8 -*-

"""
@Datetime: 2019/1/9
@Author: Zhang Yafei
"""
import json

from flask import Flask, render_template, request
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler

app = Flask(__name__)

USERS = {
    '1': {'name': '姚明', 'count': 1, 'image': 'static/images/姚明.jpg'},
    '2': {'name': '詹姆斯', 'count': 0, 'image': 'static/images/詹姆斯.jpg'},
    '3': {'name': '科比', 'count': 0, 'image': 'static/images/科比.jpg'},
}


# http://127.0.0.1:5000/index
@app.route('/index')
def index():
    return render_template('home.html', users=USERS)


WEBSOCKET_LIST = []


# http://127.0.0.1:5000/message
@app.route('/message')
def message():
    ws = request.environ.get('wsgi.websocket')
    # ws为空表示http请求，否则为websocket请求
    if not ws:
        print('http')
        return '您使用的是Http协议'
    WEBSOCKET_LIST.append(ws)
    while True:
        cid = ws.receive()
        if not cid:
            WEBSOCKET_LIST.remove(ws)
            ws.close()
            break
        old = USERS[cid]['count']
        new = old + 1
        USERS[cid]['count'] = new
        for client in WEBSOCKET_LIST:
            client.send(json.dumps({'cid': cid, 'count': new}))


if __name__ == '__main__':
    # http协议走app， websocket协议走websocket
    http_server = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    # http_server = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
    http_server.serve_forever()
